{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Markov chain \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\"LORD overthrew, and repented not: and let him say, Is it peace? And Jehu said, Unto which of all us? And he said unto him, This is the ordinance of their God: but these have altogether broken the yoke, and burst the bonds. 5:6 Wherefore a lion out of the wells of water, which Abimelech's servants had violently taken away. 21:26 And Abimelech said, Behold, my master wotteth not what is become of him. 32:2 And when Jacob had made an end of the sabbath, as it began to dawn toward the first day shall be a sign unto thee,\""
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import numpy as np\n",
    "\n",
    "class Markov:\n",
    "    def __init__ (self, order):\n",
    "        self.order = order\n",
    "        self.group_size = self.order + 1\n",
    "        self.text = None\n",
    "        self.graph = {}\n",
    "        return\n",
    "\n",
    "    def fit(self, filename): \n",
    "        self.text = open(filename).read().split() \n",
    "        self.text = self.text + self.text [:self.order]\n",
    "\n",
    "        for i in range (0, len (self.text) - self.group_size):\n",
    "            key = tuple (self.text [i : i + self.order] ) \n",
    "            value = self.text [i + self.order]\n",
    "\n",
    "            if key in self.graph:\n",
    "                self.graph[key].append (value)\n",
    "            else:\n",
    "                self.graph[key] = [value]    \n",
    "        return\n",
    "\n",
    "    def generate (self,length):\n",
    "        index = np.random.randint(0, len(self.text) - self.order)\n",
    "        result = self.text[index : index + self.order]\n",
    "\n",
    "        for i in range(length):\n",
    "            state = tuple(result[len(result) - self.order:])\n",
    "            next_word = np.random.choice(self.graph[state])\n",
    "            result.append(next_word)\n",
    "        \n",
    "        return \" \".join(result[self.order:])\n",
    "\n",
    "\n",
    "markov = Markov(3)\n",
    "markov.fit(\"data/Bible.txt\")\n",
    "markov.generate(100)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
